<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-space style="width:100%">    
        <a-button type="primary" @click="handler()">商品销售</a-button>
        <!-- <a-button type="primary" @click="handlerExcellent()">优品销售</a-button> -->
        <a-button type="primary" @click="handlerOperator()">运营商业务销售</a-button>
        <a-button type="primary" @click="handlerBothOperator()">运营商业务批量销售</a-button>    
      </a-space>
      <a-space style="width:100%;margin-top:10px">    
        <a-button type="danger" @click="handlerReturn()">商品退货</a-button>
        <!-- <a-button type="danger" @click="handlerReturn()">优品退货</a-button>0    -->
        <a-button type="danger" @click="handlerOperatorReturn()">运营商业务退货</a-button>
      </a-space>
      <a-space style="width:100%">    
        <a-input :value="goodValue" style="margin-top:10px" placeholder="扫码快速添加商品" />
      </a-space>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="销售清单">
      <a-table size="default" rowKey="key" :columns="columns" :data-source="loadData">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="type" slot-scope="text, record">
          <template>
            <div v-if="record.type == 1">{{ record.phoneCode1 }}</div>
            <div v-if="record.type == 2">
              <div>业务编码:{{ record.opBusinessId }}</div>
              <div>业务电话:{{ record.phone }}</div>
              <div>身份证号:{{ record.idCard }}</div>
              <div>酬金:系统核算</div>  
            </div>
          </template>
        </span>
        <span slot="salesType" slot-scope="text, record">
          <template v-if="record.type == 1">
            <div v-if="record.salesType == '0'">退货</div>
            <a v-if="record.salesType == '1'" @click="changeTypes(record)">售出</a>
            <a v-if="record.salesType == '2'" @click="changeTypes(record)">独立赠送</a>
            <a v-if="record.salesType == '3'" @click="changeTypes(record)">附赠</a>
            <div v-if="record.salesType == '4'">退礼品</div>
          </template>
          <template v-if="record.type == 2">
            <div>售出</div>
            <a v-if="record.salesType == '3'" @click="changeTypes(record)">业务赠送</a>
          </template>
          <div>
            <div v-if="record.salesType == '3'">{{ record.giftGoods }}</div>
          </div>
          
        </span>
        <span slot="amount" slot-scope="text, record">
          <template>
            <div v-if="record.salesType == '2' || record.salesType == '3'">0</div>
            <a @click="changePrice(record)" v-else> {{ record.amount }}</a>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
            <a-tag color="#4cae4c" @click="handleGoods(record)" v-if="record.salesType !== '0' && record.salesType !== '3' && record.salesType !== '2'">
              <a-icon type="gift" />
            </a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="form">
        <a-form-item
          label="销售员"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['empId',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择" >
            <a-select-option :value="i.id" v-for="i in userOption" :key="i.id">{{ i.userName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item 
          label="销售日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['orderDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" name="memo" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item
          label="选择会员"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-space >
            <a-input-search
              v-model="value"
              placeholder="请输入手机号或者会员卡号"
              enter-button
              @change="handleChange"
              @search="onSearch"
            />
            <a-button type="primary" @click="handAddMember()">添加</a-button>
            <a-button type="primary" v-if="JSON.stringify(this.memberDetail) !== '{}'" @click="cancel">取消</a-button>
          </a-space>
        </a-form-item>
        <a-form-item
          label="会员详情"
          v-if="JSON.stringify(this.memberDetail) !== '{}'"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-descriptions>
            <a-descriptions-item label="会员名称" :span="3">{{ memberDetail.name }}</a-descriptions-item>
            <a-descriptions-item label="会员电话" :span="3">{{ memberDetail.phone }}</a-descriptions-item>
            <a-descriptions-item label="会员卡号" :span="3">{{ memberDetail.cardNo }}</a-descriptions-item>
            <a-descriptions-item label="会员积分" :span="3">{{ memberDetail.hisBigintegral }}</a-descriptions-item>
          </a-descriptions>
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交出库</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <shop-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
      @goodsId="getGoods"
    />
    <excellent-form
      ref="excellentModal"
      :visible="excellentVisible"
      :loading="excellentLoading"
      :model="mdlExcellent"
      @cancel="handleExcellentCancel"
      @ok="handleExcellentOk"
    />
    <operator-form
      ref="operatorModal"
      :visible="operatorVisible"
      :loading="operatorLoading"
      :model="mdlOperator"
      @cancel="handleOperatorCancel"
      @ok="handleOperatorOk"
    />
    <both-form
      ref="operatorBothModal"
      :visible="operatorBothVisible"
      :loading="operatorBothLoading"
      :model="mdlBothOperator"
      @cancel="handleBothOperatorCancel"
      @ok="handleBothOperatorOk"
    />
    <return-form
      ref="returnModal"
      :visible="returnVisible"
      :loading="returnLoading"
      :model="mdlReturn"
      @cancel="handleReturnCancel"
      @ok="handleReturnOk"
      @goodsId="getGoods"
    />
    <operator-return
      ref="operatorReturnModal"
      :visible="operatorReturnVisible"
      :loading="operatorReturnLoading"
      :model="mdlOperatorReturn"
      @cancel="handleOperatorReturnCancel"
      @ok="handleOperatorReturnOk"
    />
    <add-member
      ref="addMemberModal"
      :visible="addMemberVisible"
      :loading="addMemberLoading"
      :model="addMemberMdl"
      @cancel="handleAddMemberCancel"
      @ok="handleAddMemberOk"
    />
    <goods-form
      ref="goodsModal"
      :visible="goodsVisible"
      :loading="goodsLoading"
      :model="giftMdl"
      @cancel="handleGoodsCancel"
      @ok="handleGoodsOk"
      @goodsId="getGoods"
    />
    <price-form
      ref="priceModal"
      :visible="addPriceVisible"
      :loading="addPriceLoading"
      :model="addPriceMdl"
      @cancel="handlePriceCancel"
      @ok="handlePriceOk"
    />
    <sales-type-form
      ref="saleTypeModal"
      :visible="saleTypeVisible"
      :loading="saleTypeLoading"
      :model="saleTypeMdl"
      @cancel="handleSaleTypeCancel"
      @ok="handleSaleTypeOk"
    />
  </page-header-wrapper>
</template>

<script>
import ExcellentForm from './excellentFrom'
import addMember from './addMember'
import ShopForm from './shopForm'
import OperatorForm from './operatorForm'
import bothForm from './operatorBothForm'
import returnForm from './shopReturn'
import operatorReturn from './operatorReturn'
import PriceForm from './PriceForm'
import GoodsForm from './goodsForm'
import SalesTypeForm from './salesTypeForm'
import {getEmployeesListUsingPOST} from '@/api/api/yuangongguanli.ts'
import {getMemberByNumberUsingGET,addMemberUsingPOST} from '@/api/api/huiyuanguanli.ts'
import {addSalesUsingPOST,getOpBusinessListUsingPOST1} from '@/api/api/qiantaizhangwu.ts'
import moment from 'moment'
export default {
  name: 'CashierSellDetail',
  components: {
    ShopForm,
    addMember,
    ExcellentForm,
    GoodsForm,
    SalesTypeForm,
    OperatorForm,
    bothForm,
    returnForm,
    PriceForm,
    operatorReturn
  },
  data() {
    return {
      goodsVisible:false,
      goodsLoading:false,
      saleTypeMdl:null,
      saleTypeVisible:false,
      saleTypeLoading:false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      toDays: moment().format('YYYY-MM-DD'),
      value:'',
      goodValue:'',
      goodsMdl:null,
      giftMdl:null,
      goodsDetail:{},
      addMemberMdl:null,
      returnVisible:false,
      addMemberVisible:false,
      addMemberLoading:false,
      returnLoading:false,
      mdlReturn:null,
      operatorReturnVisible:false,
      operatorReturnLoading:false,
      mdlOperatorReturn :null,
      mdl: null,
      visible: false,
      confirmLoading:false,
      addPriceMdl: null,
      addPriceVisible: false,
      addPriceLoading:false,
      mdlExcellent: null,
      excellentVisible: false,
      excellentLoading:false,
      mdlOperator: null,
      operatorVisible: false,
      operatorLoading:false,
      mdlBothOperator: null,
      operatorBothVisible: false,
      operatorBothLoading:false,
      form: this.$form.createForm(this),
      columns: [
        {
          title: '名称',
          dataIndex: 'goodName',
        },
        {
          title: '串码/运营商业务',
          dataIndex: 'phoneCode1',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '类型',
          dataIndex: 'salesType',
          scopedSlots: { customRender: 'salesType' }
        },
        {
          title: '库价(元)',
          dataIndex: 'amount',
          scopedSlots: { customRender: 'amount' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      userOption:[],
      selectedRowKeys: [],
      memberDetail:{},
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        },
      },
      queryParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      option1:[],
      optionAlertShow: false,
    }
  },
  created() {
    this.getUserOption()
    this.handle1()
  },
  methods: {
    handle1() {
      getOpBusinessListUsingPOST1(this.queryParam)
        .then((res) => {
          this.option1 = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    changeTypes(record){
      this.goodsMdl = record
      this.saleTypeVisible = true
    },
    handleSaleTypeOk(){
      const form = this.$refs.saleTypeModal.form
      form.validateFields((err, values) => {
        if (!err) {
          this.loadData.find((item) => item.inventoryId == this.goodsMdl.inventoryId).salesType = values.salesType
          this.saleTypeLoading = false
          this.saleTypeVisible = false
        }else{
          this.saleTypeLoading = false
          this.saleTypeVisible = false
        }
      })
    },
    handleSaleTypeCancel(){
      this.saleTypeVisible = false
      const form = this.$refs.saleTypeModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGoods(record){
      this.giftMdl = record
      this.goodsVisible = true
    },
    cancel(){
      this.memberDetail = {}
    },
    handleGoodsOk(){
      const form = this.$refs.goodsModal.form
      form.validateFields((err, values) => {
        if (!err) {
          const includes = this.loadData.map((item) => item.phoneCode1).includes(this.goodsDetail.phoneCode1)
          if (!!includes) {
            this.$message.error('存在相同串码')
            return false
          }
          this.loadData.push({
              amount:0,
              type:1,
              salesType:3,
              giftGoods:this.giftMdl.goodName,
              ...this.goodsDetail
            })
          this.giftMdl = null
          this.goodsLoading = false
          this.goodsVisible = false
        }else{
          this.goodsLoading = false
          this.goodsVisible = false
        }
      })
    },
    handleGoodsCancel(){
      this.goodsVisible = false
      this.giftMdl = null
      const form = this.$refs.goodsModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    changePrice(record){
      this.addPriceMdl = record
      this.addPriceVisible = true
    },
    handlePriceCancel(){
      this.addPriceVisible = false
      const form = this.$refs.priceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handlePriceOk(){
      const form = this.$refs.priceModal.form
      form.validateFields((err, values) => {
        if (!err) {
          this.loadData.find((item) => item.inventoryId == this.addPriceMdl.inventoryId).amount = values.amount
          this.addPriceLoading = false
          this.addPriceVisible = false
        }else{
          this.addPriceLoading = false
          this.addPriceVisible = false
        }
      })
    },
    handAddMember(){
      this.addMemberVisible = true
      this.addMemberLoading = false
    },
    handleAddMemberOk(){
      const form = this.$refs.addMemberModal.form
      form.validateFields((err, values) => {
        if (!err) {
          addMemberUsingPOST({...values,})
            .then((res) => {
              this.$message.success('操作成功')
              // 重置表单数据
              form.resetFields()
              this.addMemberVisible = false
              this.addMemberLoading = false
            })
            .catch((error) => {
              this.addMemberLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
    handleAddMemberCancel(){
      this.addMemberVisible = false
      const form = this.$refs.addMemberModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleMember(params) {
      getMemberByNumberUsingGET({
        number: params,
      })
        .then((res) => {
          if(res.data){
            this.memberDetail = res.data
          }else{
            this.memberDetail = {}
          }
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
 
    onSearch(value) {
      if(!value){
        this.$message.warn('请输入正确的手机号或会员卡号')
      }
      this.handleMember(value)
    },
    handleChange(e) {
      this.value = e.target.value
    },
    getUserOption() {
      getEmployeesListUsingPOST(this.optionParam)
        .then((res) => {
          this.userOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    getGoods(data){
      this.goodsDetail = data
    },
    handleDel(record){
        const that = this
        that.$confirm({
          title: '删除',
          content: '你确定要删除这个商品吗？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            that.loadData.splice( that.loadData.findIndex(item => item.id === record.id), 1)
            // this.loadData = this.loadData
          },
        })
      },
    handler(){
      this.visible = true
      this.confirmLoading = false
    },
    handlerExcellent(){
      this.excellentVisible = true
      this.excellentLoading = false
    },
    handlerOperator(){
      this.operatorVisible = true
      this.operatorLoading = false
    },
    handlerBothOperator(){
      this.operatorBothVisible = true
      this.operatorBothLoading = false
    },
    handlerReturn(){
      this.returnVisible = true
      this.returnLoading = false
    },
    handlerOperatorReturn(){
      this.operatorReturnVisible = true
      this.operatorReturnLoading = false
    },
    handleOk () {
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
         this.loadData.push({
              ...values,
              type:1,
              amount:values.amount,
              salesType:1,
              ...this.goodsDetail
            })
          this.visible = false
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleExcellentOk () {
      this.excellentVisible = false
      this.excellentLoading = true
      setTimeout(() => {
        this.excellentLoading = false
      }, 1000)
      this.$message.success('操作成功')
    },
    handleExcellentCancel () {
      this.excellentVisible = false
      const form = this.$refs.excellentModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleOperatorOk () {
      const form = this.$refs.operatorModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
         this.loadData.push({
              ...values,
              ...this.goodsDetail,
              type:2,
              amount:values.amount,
              salesType:1,
              goodName:this.option1.find((item) => item.id === values.opBusinessId).name,
            })
          this.operatorVisible = false
        } else {
          this.operatorLoading = false
        }
      })
    
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    handleOperatorCancel () {
      this.operatorVisible = false
      const form = this.$refs.operatorModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleBothOperatorOk () {
      const form = this.$refs.operatorBothModal.form
      form.validateFields((errors, values) => {
        if (!errors) { 
         this.removeTrim(values.phone.split('\n')).map((item)=>{
          this.loadData.push({
              ...values,
              ...this.goodsDetail,
              type:2,
              phone:item.split(' ').filter(m=>m )?.[0],
              idCard:item.split(' ').filter(m=>m )?.[1],
              amount:values.amount,
              salesType:0,
              goodName:this.option1.find((item) => item.id === values.opBusinessId).name,
            })
         })
          this.operatorBothVisible = false
        } else {
          this.operatorBothLoading = false
        }
      })
    },
    handleBothOperatorCancel () {
      this.operatorBothVisible = false
      const form = this.$refs.operatorBothModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleReturnOk () {
      const form = this.$refs.returnModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
         this.loadData.push({
              ...values,
              ...this.goodsDetail,
              amount:`-${values.amount}`,
              salesType:'0',
              type:1,
            })
          this.returnVisible = false
        } else {
          this.returnLoading = false
        }
      })
    },
    handleReturnCancel () {
      this.returnVisible = false
      const form = this.$refs.returnModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleOperatorReturnOk () {
      const form = this.$refs.operatorReturnModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
         this.loadData.push({
              ...values,
              type:2,
              amount:values.amount,
              salesType:'0',
              goodName:this.option1.find((item) => item.id === values.goodName).name,
              ...this.goodsDetail
            })
          this.operatorReturnVisible = false
        } else {
          this.operatorReturnLoading = false
        }
      })
    },
    handleOperatorReturnCancel () {
      this.operatorReturnVisible = false
      const form = this.$refs.operatorReturnModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) { 
          // if(JSON.stringify(this.memberDetail) == '{}'){
          //   this.$message.success('请选择会员')
          //   return false
          // }
          if(this.loadData.length == 0) {
            this.$message.error('没有添加销售商品')
            return false
          }
          const queryParams = {
            ...values,
            storeId:this.$route.params.id,
            memId:this.memberDetail.id,
            memo: values.memo,
            orderDate: values.orderDate
          }
          const params = {
            salesListParams: this.loadData.map((item) => {
             if(item.type == 1 && item.salesType !== 3){
              return {
               ...item,
               amount:item.amount,
               isGift:item.salesType ==  '2' ? 1 : 0,
               salDetailList:this.loadData.filter((i) => i.salesType === 3).map((j) => {
                return {
                  ...j,
                  isGift:1,
                }
               })
              }
             }
            }).filter((item)=> item),
            opBusinessParams: this.loadData.map((item) => {
             if(item.type == 2 && item.salesType !== 3){
              return {
               ...item,
               salesType:item.salesType ==  '0' ? 0 : 1,
               isGift:item.salesType ==  '2' ? 1 : 0,
               amount:item.amount,
               salDetailList:this.loadData.filter((i) => i.salesType === 3).map((j) => {
                return {
                  ...j,
                  isGift:1,
                }
               })
              }
             }
            }).filter((item)=> item),
           
          }
          addSalesUsingPOST({...queryParams}, { ...params })
            .then((res) => {
              this.$message.success('操作成功')
              if(res.data.amount == '0'){
                this.$router.push({ path: `/cashier/profile/index/${res.data.id}` })
              }else{
                this.$router.push({ path: `/cashier/profile/order/${res.data.id}` })
              }
              // 重置表单数据
              this.form.resetFields()
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
 
}
</script>
